package cn.eaay.stock.common.pull;

import cn.eaay.stock.common.constants.StockConstants;
import cn.eaay.stock.dto.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用于拉取远程股票API数据的服务
 */
@Slf4j
@Component
public class PullRemoteStockApiDataService {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 使用默认参数，拉取远程数据
     *
     * @param url API地址
     * @return
     */
    public JsonResult pullApi(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + StockConstants.STOCK_API_APP_CODE);
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity(headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JsonResult.class);
        return responseEntity.getBody();
    }

    /**
     * 使用默认参数，拉取远程数据
     *
     * @param url  API地址
     * @param code 携带参数
     * @return
     */
    public JsonResult pullApi(String url, String code) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + StockConstants.STOCK_API_APP_CODE);
        MultiValueMap<String, String> paramMap = new LinkedMultiValueMap();
        paramMap.add("code", code);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(paramMap, headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, JsonResult.class);
        return responseEntity.getBody();
    }

    /**
     * 自定参数，获取API数据
     *
     * @param url
     * @param method
     * @param headers
     * @param clazz
     * @param params
     * @return
     */
    public <T> T pullApi(String url, HttpMethod method, HttpHeaders headers, Class<T> clazz, String... params) {
        HttpEntity<Map<String, String>> httpEntity = new HttpEntity(headers);
        ResponseEntity<T> responseEntity = restTemplate.exchange(url, method, httpEntity, clazz);
        return responseEntity.getBody();
    }
}
